<template>
  <div class="data-card">
    <div class="text-content">
      <div class="title">{{ data.title }}</div>
      <div class="number">{{ data.number.toLocaleString() }}</div>
      <div class="percentage" :class="{'positive': data.percentage >= 0, 'negative': data.percentage < 0}">
        {{ data.percentage }}%
      </div>
    </div>
    <div class="chart-content">
      <canvas ref="lineChart"></canvas>
    </div>
  </div>
</template>

<script>
import {defineComponent, ref, onMounted, watch} from 'vue';
import Chart from 'chart.js/auto';

export default defineComponent({
  name: 'DataCard',
  props: {
    data: {
      type: Object,
      required: true
    },
    time: {
      type: String,
      required: true
    }
  },
  setup(props) {
    const lineChart = ref(null);

    let chartInstance = null;

    const createChart = () => {
      if (chartInstance) {
        chartInstance.destroy();
      }

      chartInstance = new Chart(lineChart.value, {
        type: 'line',
        data: {
          labels: props.data.chartData.labels,
          datasets: [{
            data: props.data.chartData.data,
            borderColor: '#9adefa',
            fill: false
          }]
        },
        options: {
          responsive: true,
          maintainAspectRatio: false,
          scales: {
            x: {
              display: false
            },
            y: {
              display: false
            }
          },
          elements: {
            line: {
              tension: 0.4
            }
          },
          plugins: {
            legend: {
              display: false
            }
          }
        }
      });
    }
    onMounted(() => {
      createChart();
    });

    watch(() => props.time, () => {
      createChart();
    });

    return { lineChart };
  }
});
</script>

<style scoped>
.data-card {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  padding: 16px;
  width: 250px;
  height: 100px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.text-content {
  display: flex;
  flex-direction: column;
  justify-content: center;
  width: 100px;
  max-width: 100px;
/*  margin-right: 16px;*/
}

.title {
  font-size: 16px;
  margin-bottom: 4px;
}

.number {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 6px;
  margin-top: 10px;
}

.percentage {
  font-weight: 600;
  font-size: 16px;
  margin-top: 5px;
}

.percentage.positive {
  color: #00c400;
}

.percentage.negative {
  color: red;
}

.chart-content {
  flex: 1;
  display: flex;
  align-items: center;
  height: 80%;
}

canvas {
  width: 100%;
  height: 100%;
}
</style>
